<script setup>
import { userRegisterService,userLoginService } from '@/api/userLogin'
//注意导入路径
import { User, Lock } from '@element-plus/icons-vue'
import { ref, watch} from 'vue'
import {useUserStore} from '@/stores/modules/user'
import { useRoute, useRouter } from 'vue-router'
const isRegister = ref(false)
 
//用于提交的数据对象
// (1) el-form => :model="ruleForm"绑定的整个form的数据对象{ xxx，xxx，xxx }
// (2) el-form => :rules="rules"绑定的整个rules规则对象{ xxx，xxx，xxx }
// （3）表单元素=>v-model="ruleForm.xxx"给表单元素，绑定form的子属性
// (4）el-form-item => prop配置生效的是哪个校验规则（和rules中的字段要对应)
//整个表单的校验规则
const formModel = ref({
    username:'',
    password:'',
    repassword:''
})
//非空校验:required  提示消息:message 触发时机：trigger
//正则校验pattern
//自定义校验：validator:(rele(当前校验规则),value(所校验表单元素目前表单值),callback(校验结果处理，无论失败都需要回调函数))=>{}
const rules = {
    username:[
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { max:10, message:'用户名长度必须小于等于10'}
    ],
    password:[
        { required: true, message: '请输入密码', trigger: 'blur' },
        { pattern:/^\S{6,15}$/, message:'密码长度因是6~12位非空字符'}
    ],
    repassword:[
        {validator:(rele,value,callback)=>{if(value!=formModel.value.password){callback(new Error('两次输入不一致'))}else{callback()}},trigger:'blur'}
    ]
}

//注册预校验
const form = ref()
const  register = async ()=>{
  await form.value.validate()
  //注册请求
  await userRegisterService(formModel.value)
  ElMessage.success('注册成功')
  isRegister.value = false
}

//在登陆时，由于绑定使用了相同的form，所有在切换注册和登录时，会出现登录框和密码框共用数据的情况，因此需要在使用时重置表单
//通过watch监视isRegister的变化来判断是否发生了注册和登录的变化
watch(isRegister,()=>{
  formModel.value = {
    username:'',
    password:'',
    repassword:''
  }
})
//登陆方法
//保存返回token值
const userStore= useUserStore()
//路由实例化
const router = useRouter()
const login = async()=>{
  // 使用预校验必须要在对应表单中加入ref
  await form.value.validate()
  //注册请求
  const res = await userLoginService(formModel.value)
  userStore.setToken(res.data.token)
  ElMessage.success('登录成功')
  //跳转
  router.push('/')
}

</script>

<template>
    <el-row class="login-page">
      <el-col :span="12" class="bg"></el-col>
      <el-col :span="6" :offset="3" class="form">

        <!-- 注册 -->
        <!-- el-form标签绑定必须使用:model而不是v-model -->
        <!-- 表单中绑定ref -->
        <el-form 
         :model="formModel"
         :rules='rules'
         ref="form"
         size="large"
         autocomplete="off" 
         v-if="isRegister"
        >
          <el-form-item>
            <h1>注册</h1>
          </el-form-item>

          <el-form-item prop="username">
            <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="formModel.password"
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入密码"
              show-password
            ></el-input>
          </el-form-item>

          <el-form-item prop="repassword">
            <el-input
              v-model="formModel.repassword"
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入再次密码"
              show-password 
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button @click="register" class="button" type="primary" auto-insert-space >
              注册
            </el-button>
          </el-form-item>
          <el-form-item class="flex">
            <el-link type="info" :underline="false" @click="isRegister = false">
              ← 返回
            </el-link>
          </el-form-item>
        </el-form>
         <!-- 登录 -->
         <!-- el-form标签绑定必须使用:model而不是v-model -->
         <!-- 表单中绑定ref -->
        <el-form 
         :model="formModel"
         :rules = 'rules'
         ref="form" 
         size="large" 
         autocomplete="off" 
         v-else
        >
          <el-form-item>
            <h1>登录</h1>
          </el-form-item>
          <el-form-item prop="username">
            <el-input 
             v-model="formModel.username"
             :prefix-icon="User" 
             placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="formModel.password"
              name="password"
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item class="flex">
            <div class="flex">
              <el-checkbox>记住我</el-checkbox>
              <el-link type="primary" :underline="false">忘记密码？</el-link>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button @click="login" class="button" type="primary" auto-insert-space
              >登录</el-button
            >
          </el-form-item>
          <el-form-item class="flex">
            <el-link type="info" :underline="false" @click="isRegister = true">
              注册 →
            </el-link>
          </el-form-item>
        </el-form>

      </el-col>
    </el-row>
  </template>

<style scoped>
/* 注意，此处可以使用sass样式管理而并非一定需要原生css */
.login-page {
  height: 100vh;
  background-color: #fff;
}
.bg {
    background:url('@/assets/欢迎.png') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
}
.form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
}
.title {
      margin: 0 auto;
}
.button {
      width: 100%;
}
.flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
}
</style>